#coding:utf-8
import json
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from lovewith.account.views.modules.noticeapi import NoticeApi
from lovewith.api.dxw_sms_tools import DxwSmsApi
from lovewith.api.qiniu import Qiniu
from lovewith.share.views.modules.attach import AttachApi
from lovewith.share.views.modules.share import ShareApi
from lovewith.supplier.views.modules.reserveapi import ReserveApi
from lovewith.supplier.views.modules.supplierapi import SupplierApi
from lovewith.utils.image import MtImage
from lovewith.utils.upload import Upload
from lovewith.website.views.modules.province import ProvinceApi


def get_supplier_list(request):
    page_no = int(request.GET.get('page', 1))
    city_id = request.GET.get('city_id')
    city_name = request.GET.get('city_name')
    service_id = request.GET.get('service', 'all')

    supplier_data = []

    if not city_id:
        if city_name:
            city_data = ProvinceApi.check_by_name(city_name=city_name)
            if city_data:
                city_id = city_data.id
        else:
            city_id = 'all'
    else:
        city_id = int(city_id)

    if page_no and city_id:
        supplier_data = SupplierApi.get_suppliers_post(city_id=city_id, page_no=page_no, service_id=service_id)

    return HttpResponse(json.dumps(supplier_data))


#增加预约记录
@login_required
def add_reserve(request):
    user = request.user
    expected_date = request.POST.get('date')
    city = request.POST.get('city')
    content = request.POST.get('content')
    supplier_uid = request.POST.get('sid')
    post_id = request.POST.get('pid' or None)
    wedding_date = request.POST.get('wed_date')
    user_role = request.POST.get('user_role')
    post_data = None

    if post_id:
        post_data = ShareApi.check_data(int(post_id))

    if supplier_uid and post_data:
        supplier_data = SupplierApi.check_data(int(supplier_uid))
        if supplier_data and expected_date and city and wedding_date:
            ReserveApi.add(
                phone=user.phone,
                city=city,
                expected_date=expected_date,
                supplier=supplier_data,
                content=content,
                user=user,
            )

            phone = supplier_data.business_tel or supplier_data.phone

            #发送通知给用户
            NoticeApi.send(
                type='system',
                title=u'您预约了[b]%s[/b]' % post_data.title,
                content=u'<p>您预约了[b]%s[/b] [b]%s[/b]稍后会与您联系，您也可以通过以下方式与商家联系。</p>'
                        u'<p>商家服务电话：%s</p>'
                        u'<p>您的预约信息如下：</p>'
                        u'<p>预约城市：%s</p>'
                        u'<p>预约时间：%s</p>' % (post_data.title, post_data.user.username, phone, city, expected_date),
                receiver=user
            )
            #发送短信通知
            sms_message = u'您预约了%s %s稍后会与您联系，您也可以通过以下方式与商家联系： %s' % \
                          (post_data.title, post_data.user.username, phone)
            DxwSmsApi().send(user.phone, sms_message)

            sex = u'她'
            if user_role == '1':
                sex = u'他'

            #发通知给服务商
            NoticeApi.send(
                type='system',
                title=u'[b]%s[/b] 预约了[b]%s[/b]' % (user.full_name, post_data.title),
                content=u'<p>[b]%s[/b] 预约了[b]%s[/b] 请尽快与%s联系。</p>'
                        u'<p>预约人姓名：%s</p>'
                        u'<p>预约人电话：%s</p>'
                        u'<p>预约时间：%s</p>'
                        u'<p>预约城市：%s</p>'
                        u'<p>婚期：%s</p>' % (
                            user.full_name, post_data.title, sex, user.full_name, user.phone, expected_date, city,
                            wedding_date),
                receiver=supplier_data.user
            )
            #发送短信通知
            sms_message = u'%s[%s] 预约了%s，请尽快与%s联系' % \
                          (user.full_name, user.phone, post_data.title, sex)
            DxwSmsApi().send(supplier_data.phone, sms_message)

            return HttpResponse(json.dumps({'error': False, 'tel': phone}))

    return HttpResponse(json.dumps({'error': True}))


#根据图片获取服务商
# def get_by_image(request):
#     city_name = request.GET.get('city')
#     image_id = request.GET.get('mid')
#     #推荐的服务商数据
#     recommand_supplier_data = []
#
#     if city_name and image_id:
#         service_type_id = []
#         service_type_data = AttachApi.get_service_type(int(image_id))
#         city_data = ProvinceApi.check_by_name(city_name=city_name)
#
#         if service_type_data and city_data:
#             for cid in service_type_data:
#                 service_type_id.append(cid.service.id)
#
#         if len(service_type_id) > 0:
#             supplier_ids = SupplierApi.get_by_image(service_type_id, city_data.id)
#             for supplier in supplier_ids:
#                 supplier_data = SupplierApi.check_data(supplier_id=supplier['id'])
#                 recommand_supplier_data.append({
#                     'uid': supplier_data.user_id,
#                     'username': supplier_data.company,
#                     'avatar': supplier_data.user.avatar
#                 })
#
#     return HttpResponse(json.dumps(recommand_supplier_data))


#上传服务商banner
@login_required
def upload_supplier_banner(request):
    attach = request.FILES.get('file', None)
    image_path = Upload().save_files(attach, blur=True)

    return HttpResponse(image_path)


#修改banner
@login_required
def save_supplier_banner(request):
    banner = request.POST.get('banner')
    img_width = request.POST.get('imgWidth')
    img_height = request.POST.get('imgHeight')
    mask_y = request.POST.get('maskTop')
    mask_x = request.POST.get('maskLeft')
    banner_y = request.POST.get('bannerTop')
    banner_x = request.POST.get('bannerLeft')

    #判断用户是否属于服务商
    suplier_data = SupplierApi.check_data(request.user.id)
    if suplier_data and request.user.group_id == 3:
        if banner and img_width and img_height and mask_y and mask_x and banner_y and banner_x:
            img_height = int(img_height)
            img_width = int(img_width)
            mask_y = int(mask_y)
            mask_x = int(mask_x)
            banner_y = int(banner_y)
            banner_x = int(banner_x)

            banner_path = MtImage().scale_and_crop(banner, img_width, img_height, banner_x, banner_y, 780, 380)
            mask_path = MtImage().scale_and_crop(
                banner.replace('.jpg', '_mask.jpg'),
                img_width,
                img_height,
                mask_x,
                mask_y,
                400,
                380
            )

            #上传图片到upyun
            new_banner_path = Qiniu('mt-other').upload(banner_path)
            new_mask_path = Qiniu('mt-other').upload(mask_path)

            #删除原图
            if suplier_data.home_banner:
                Qiniu('mt-other').delete(suplier_data.home_banner)
            #删除mask
            if suplier_data.banner_mask:
                Qiniu('mt-other').delete(suplier_data.banner_mask)

            suplier_data.home_banner = new_banner_path['path']
            suplier_data.banner_mask = new_mask_path['path']
            suplier_data.save()

    return HttpResponse(json.dumps({'error': False}))


#删除商家服务分类
@login_required
def del_supplier_service(request):
    supplier_id = request.GET.get('suid' or 0)
    service_id = request.GET.get('seid' or 0)

    if request.user.is_admin and supplier_id and service_id:
        supplier_service = SupplierApi.get_service_type(int(supplier_id), int(service_id))
        if supplier_service:
            supplier_service.delete()


    return HttpResponse(json.dumps({'error': False}))